<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Purchase\PurchaseStockinOrder as PurchasePurchaseStockinOrder;
use App\Models\Common\EditLog;
use App\Models\Custom\Custom;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchaseOrderProcessSub;
use App\Models\Purchase\PurchaseOrderSub;
use App\Models\Purchase\PurchaseStockinOrder;
use App\Models\Purchase\PurchaseStockinOrderSub;
use App\Models\Purchase\PurchaseWarehousingOrder;
use App\Models\Purchase\PurchaseWarehousingOrderSub;
use App\Models\Purchase\PurchaseWarehousingOrderwithpay;
use App\Models\Stock\StockSub;
use App\Models\Warehouse\WarehouseList;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use App\Services\Purchase\PurchaseCommon;
use App\Services\Stock\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 进货单
 */
class PurchaseStockinOrderController extends BaseController
{

    /**
     * 获取表头
     *
     * @param Request $request
     * @return void
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new PurchaseStockinOrder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new PurchaseStockinOrderSub())->getTable(), $cpid);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['mainextfield' => $mainextfield, 'subextfield' => $subextfield]]);
    }

    /**
     * 进货单列表
     */
    public function getorderlist(Request $request)
    {
        $isgetall = $request->isgetall ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseStockinOrder::getList($request, $cpid, $manger_id, $isgetall);
        //销售订单号获取
        if($list['list']){
            foreach ($list['list'] as $key => $value) {
                $list['list'][$key]['sale_order_number'] = '';
                if(!empty($value['order_id'])){
                    $list['list'][$key]['sale_order_number'] = PurchaseOrder::where('id',$value['order_id'])->value('sale_order_number');
                }
            }
        }
        //计算子订单数据到主订单
        $list['list'] = PurchaseCommon::getOrderSum($list['list']);

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 获取订单详情
     */
    public function getorderinfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with(['suborder', 'createmangerinfo','mangerinfo'])->first();
        $info['sale_order_number'] = '';
        if(isset($info['order_id'])){
            $info['sale_order_number'] = PurchaseOrder::where('id',$info['order_id'])->value('sale_order_number');
        }
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }

    /**
     * 修改进货单
     * 结算模式为：锁价/点价/后结算，
     * 锁价后单价不进行修改，锁单价（基价+加价）在当天
     * 选择点价，增加时间，添加时间（精确到天）
     * 后结算采购**订单付款按钮置灰**，后续流程中的单价只有后结算模式可修改，其他模式不变
     */
    public function dopostedit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $remark = $request->remark ?? '';
        if ($this->mangerinfo['utype'] == 4) {
            $info = PurchaseStockinOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        } else {
            $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        }

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可修改']);
        }

        //修改的信息只可修改子订单信息

        if ($this->mangerinfo['utype'] == 6 && $info->is_finance_update != 1) {
            return response()->json(['code' => '001', 'msg' => '财务修改后，采购不可修改']);
        }

        $suborder = is_array($request->suborder) ? $request->suborder : (is_array(json_decode($request->suborder, true)) ? json_decode($request->suborder, true) : []);
        if (count($suborder) <= 0) {
            return response()->json(['code' => '001', 'msg' => '订单数据不能为空']);
        }
        $cpid = $this->mangerinfo['cpid'];
        $ValidateSub = new PurchasePurchaseStockinOrder();
        $suborderdata = [];
        $order_weight = 0;
        $order_count = 0;
        $order_money = 0;
        $order_weight_old = 0;
        $order_count_old = 0;
        $order_money_old = 0;
        $suborderkey = [];
        foreach ($suborder as $s_order) {
            $s_order = is_array($s_order) ? $s_order : json_decode($s_order, true);
            if (!$ValidateSub->check($s_order)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            //判断子订单是否存在
            $suborderinfo = PurchaseStockinOrderSub::where(['cpid' => $cpid, 'stockin_order_id' => $order_id, 'id' => $s_order['id'], 'is_del' => 1])->first();
            if (!$suborderinfo || $s_order['stock_id'] != $suborderinfo->stock_id) { //只可修改件数，重量等相关数据
                return response()->json(['code' => '001', 'msg' => '无效参数']);
            }
            $suborderinfo = $suborderinfo->toArray();

            $suborderinfo['total_weight'] = mathfuncweight('mul', $suborderinfo['total_weight'], 10); //kg*10

            $order_weight_old = mathfuncweight('add', $order_weight_old, $suborderinfo['total_weight']);
            $order_count_old = mathfunc('add', $order_count_old, $suborderinfo['count']);
            $order_money_old = mathfuncmoney('add', $order_money_old, intval($suborderinfo['total_money']));

            $suborderkey[] = $suborderinfo['id'];
            if ($suborderinfo['create_status'] != 1) { //如已生成则不可修改数据跳过
                $order_weight = mathfuncweight('add', $order_weight, $suborderinfo['total_weight']);
                $order_count = mathfunc('add', $order_count, $suborderinfo['count']);
                $order_money = mathfuncmoney('add', $order_money, intval($suborderinfo['total_money']));
                continue;
            }

            $update_item = [];
            if ($suborderinfo['archive_type'] == 3) { //定尺
                $suborderinfo['weight'] = mathfuncweight('mul', $suborderinfo['weight'], 10); //kg*10
                $total_weight = mathfuncweight('mul', $suborderinfo['weight'], $s_order['count']); //kg*10
                $update_item['total_weight'] = $total_weight; //kg*10
                $update_item['count'] =  $s_order['count'];
            } elseif ($suborderinfo['archive_type'] == 1 || $suborderinfo['archive_type'] == 2) { //过磅//理计，理计初始化和过磅一样，取总重和件数
                $total_weight = mathfuncweight('mul', $s_order['total_weight'], 10); //kg*10
                $update_item['total_weight'] = $total_weight; //kg*10
                $update_item['count'] =  $s_order['count'];
                $update_item['weight'] = mathfuncweight('div', $s_order['total_weight'], $s_order['count']); //kg*10
            }



            if ($info->is_band != 1) { //创建订单未绑定协议的，可以修改价格
                if (!(isset($s_order['base_price']) && intval($s_order['base_price']) > 0) || !(isset($s_order['add_price']) && intval($s_order['add_price']) >= 0)) {
                    return response()->json(['code' => '001', 'msg' => '无效价格设置']);
                }

                $sub_order_info['base_price'] =  $s_order['base_price'];
                $sub_order_info['add_price'] =  $s_order['add_price'];
                $sub_order_info['price'] =  mathfuncmoney('add', $s_order['base_price'], $s_order['add_price']);


                $update_item['base_price'] = $sub_order_info['base_price'];
                $update_item['add_price'] = $sub_order_info['add_price'];
                $update_item['price'] = $sub_order_info['price'];
            }

            $update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 10000, 5), $suborderinfo['price'], 0);

            $update_item['changedata'] = [
                'total_money' => mathfuncmoney('sub', $update_item['total_money'], $suborderinfo['total_money']),
                'count' => mathfunc('sub', $update_item['count'], $suborderinfo['count']),
                'total_weight' => mathfuncweight('sub', $update_item['total_weight'], $suborderinfo['total_weight'])
            ];
            $order_weight = mathfuncweight('add', $order_weight, $total_weight);
            $order_count = mathfunc('add', $order_count, $update_item['count']);
            $order_money = mathfuncmoney('add', $order_money, intval($update_item['total_money']));
            $update_item['sub_order_id'] = $suborderinfo['sub_order_id'];
            $update_item['stock_id'] = $suborderinfo['stock_id'];

            $update_item['remark'] = isset($s_order['remark']) ? $s_order['remark'] : '';

            $suborderdata[$suborderinfo['id']] = $update_item;
        }


        if(count($suborderdata)<=0){
            return response()->json(['code' => '001', 'msg' => '当期没有可以修改的数据']);
        }
        // print_r($suborderdata);exit;
        DB::beginTransaction();
        try {
            foreach ($suborderdata as $key => $val) {

                PurchaseOrderProcessSub::where(['cpid' => $cpid, 'sub_order_id' => $val['sub_order_id']])->update(
                    [
                        'stockin_weight' => DB::raw('stockin_weight + ' . $val['changedata']['total_weight']),
                        'stockin_count' => DB::raw('stockin_count + ' . $val['changedata']['count']),
                        'stockin_money' => DB::raw('stockin_money + ' . $val['changedata']['total_money'])
                    ]
                );
                //处理待入库相关数据
                 Stock::doStockIn($cpid, $val['stock_id'], $val['changedata']['count'], $val['changedata']['total_weight']);

                unset($val['changedata']);
                unset($val['sub_order_id']);
                unset($val['stock_id']);
                PurchaseStockinOrderSub::where(['cpid' => $cpid, 'stockin_order_id' => $order_id, 'id' => $key])->update($val);
            }
            /**
             * 处理订单进度
             */
            PurchaseOrderProcess::where(['cpid' => $cpid, 'order_id' => $info->order_id])->update([
                'stockin_weight' => DB::raw('stockin_weight + ' . mathfunc('sub', $order_weight, $order_weight_old)),
                'stockin_count' => DB::raw('stockin_count + ' . mathfunc('sub', $order_count, $order_count_old)),
                'stockin_money' => DB::raw('stockin_money + ' . mathfunc('sub', $order_money, $order_money_old))
            ]);

            if ($this->mangerinfo['utype'] == 4) {
                PurchaseStockinOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->update(['is_finance_update' => 2, 'remark' => $remark, 'update_at' => time()]);
            } else {
                PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update(['remark' => $remark, 'update_at' => time()]);
            }



            $editlog = ['cpid' => $cpid, 'order_type' => 2, 'order_sn_code' => $info->order_sn_code, 'before_data' => json_encode($info), 'editor_mid' => $this->mangerinfo['id'], 'editor_realname' => $this->mangerinfo['realname'], 'create_at' => time()];
            $editlog['after_data'] = json_encode(PurchaseStockinOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first());

            EditLog::create($editlog);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订编辑失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 删除订单
     */
    public function doorderdel(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可删除']);
        }
        $subcount = PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid], ['create_status', '<>', 1]])->count();

        if ($subcount > 0) {
            return response()->json(['code' => '001', 'msg' => '存在已生成订单']);
        }

        DB::beginTransaction();
        try {

            //只更新订单删除状态。不处理库存相关内容

            //审核通过处理库存相关内容



            //更新订单执行情况
            $sublist = PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id])->get()->toArray();
            $stockin_weight = 0;
            $stockin_count = 0;
            $stockin_money = 0;
            foreach ($sublist as $val) {
                $val['total_weight'] = mathfuncweight('mul', $val['total_weight'], 10); //kg*10
                $stockin_weight = mathfuncweight('add', $stockin_weight, $val['total_weight']);
                $stockin_count = mathfunc('add', $stockin_count, $val['count']);
                $stockin_money = mathfuncmoney('add', $stockin_money, $val['total_money']);
                PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])
                    ->update([
                        'stockin_weight' => DB::raw('stockin_weight - ' . $val['total_weight']),
                        'stockin_count' => DB::raw('stockin_count - ' . $val['count']),
                        'stockin_money' => DB::raw('stockin_money - ' . $val['total_money'])
                    ]);
                PurchaseOrderSub::where([['order_id', $info->order_id], ['cpid', $cpid], ['id', $val['sub_order_id']]])
                    ->update(['create_count' => DB::raw('create_count + ' . $val['count']), 'create_weight' => DB::raw('create_weight - ' . $val['total_weight'])]);

                // //处理待入库相关数据
                // Stock::doStockIn($cpid, $val['stock_id'], -$val['count'], -$val['total_weight']);
            }
            PurchaseOrderProcess::where([['order_id', $info->order_id], ['cpid', $cpid]])
                ->update([
                    'stockin_weight' => DB::raw('stockin_weight - ' . $stockin_weight),
                    'stockin_count' => DB::raw('stockin_count - ' . $stockin_count),
                    'stockin_money' => DB::raw('stockin_money - ' . $stockin_money)
                ]);

            PurchaseStockinOrder::where(['id' => $order_id,  'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);
            PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);


            // PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->update(['del_audit_status' => 2]);
            // PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id])->update(['del_audit_status' => 2]);
            //处理待入库相关

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单删除失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function doorderdelaudit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $del_audit_status = $request->del_audit_status ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseStockinOrder::where(['id' => $order_id,  'cpid' => $cpid])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if (!in_array($del_audit_status, [3, 4])) {
            return response()->json(['code' => '001', 'msg' => '审核参数错误']);
        }

        if ($info->del_audit_status == 1) {
            return response()->json(['code' => '001', 'msg' => '订单未提交审核']);
        }
        if (in_array($info->del_audit_status, [3, 4])) {
            return response()->json(['code' => '001', 'msg' => '订单已审核']);
        }



        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可删除']);
        }
        $subcount = PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid], ['create_status', '<>', 1]])->count();

        if ($subcount > 0) {
            return response()->json(['code' => '001', 'msg' => '存在已生成订单']);
        }






        DB::beginTransaction();
        try {
            //审核通过处理库存相关内容

            if ($del_audit_status == 3) {
                //更新订单执行情况
                $sublist = PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id])->get()->toArray();
                $stockin_weight = 0;
                $stockin_count = 0;
                $stockin_money = 0;
                foreach ($sublist as $val) {
                    $val['total_weight'] = mathfuncweight('mul', $val['total_weight'], 10); //kg*10
                    $stockin_weight = mathfuncweight('add', $stockin_weight, $val['total_weight']);
                    $stockin_count = mathfunc('add', $stockin_count, $val['count']);
                    $stockin_money = mathfuncmoney('add', $stockin_money, $val['total_money']);
                    PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])
                        ->update([
                            'stockin_weight' => DB::raw('stockin_weight - ' . $val['total_weight']),
                            'stockin_count' => DB::raw('stockin_count - ' . $val['count']),
                            'stockin_money' => DB::raw('stockin_money - ' . $val['total_money'])
                        ]);
                    PurchaseOrderSub::where([['order_id', $info->order_id], ['cpid', $cpid], ['id', $val['sub_order_id']]])
                        ->update(['create_count' => DB::raw('create_count + ' . $val['count']), 'create_weight' => DB::raw('create_weight - ' . $val['total_weight'])]);

                    // //处理待入库相关数据
                    // Stock::doStockIn($cpid, $val['stock_id'], -$val['count'], -$val['total_weight']);
                }
                PurchaseOrderProcess::where([['order_id', $info->order_id], ['cpid', $cpid]])
                    ->update([
                        'stockin_weight' => DB::raw('stockin_weight - ' . $stockin_weight),
                        'stockin_count' => DB::raw('stockin_count - ' . $stockin_count),
                        'stockin_money' => DB::raw('stockin_money - ' . $stockin_money)
                    ]);

                PurchaseStockinOrder::where(['id' => $order_id,  'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time(), 'del_audit_status' => 3]);
                PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);
            } else {
                PurchaseStockinOrder::where(['id' => $order_id,  'cpid' => $cpid])->update(['del_audit_status' => 4]);
            }




            //处理待入库相关

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单删除失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 批量删除
     */
    public function doorderdelmore(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
        if (count($order_id_arr) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $delcount = PurchaseStockinOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid])->whereIn('id', $order_id_arr)->count();
        if (count($order_id_arr) != $delcount) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $subcount = PurchaseStockinOrderSub::where([['cpid', $cpid], ['create_status', '<>', 1]])->whereIn('stockin_order_id', $order_id_arr)->count();

        if ($subcount > 0) {
            return response()->json(['code' => '001', 'msg' => '存在已生成订单']);
        }

        DB::beginTransaction();
        try {
            //更新订单执行情况
            $orderlist = PurchaseStockinOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid])->whereIn('id', $order_id_arr)->get()->toArray();
            foreach ($orderlist as $order) {

                //判断是否完结
                $finishcount = PurchaseOrderProcess::where(['order_id' => $order['order_id'],  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
                if ($finishcount > 0) {
                    // return response()->json(['code' => '001', 'msg' => '订单已完结，不可删除']);
                    throw new \Exception('订单已完结，不可删除');
                }

                $sublist = PurchaseStockinOrderSub::where(['stockin_order_id' => $order['id']])->get()->toArray();
                $stockin_weight = 0;
                $stockin_count = 0;
                $stockin_money = 0;
                foreach ($sublist as $val) {
                    $val['total_weight'] = mathfuncweight('mul', $val['total_weight'], 10);
                    $stockin_weight = mathfuncweight('add', $stockin_weight, $val['total_weight']);
                    $stockin_count = mathfunc('add', $stockin_count, $val['count']);
                    $stockin_money = mathfuncmoney('add', $stockin_money, $val['total_money']);
                    PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])
                        ->update([
                            'stockin_weight' => DB::raw('stockin_weight - ' . $val['total_weight']),
                            'stockin_count' => DB::raw('stockin_count - ' . $val['count']),
                            'stockin_money' => DB::raw('stockin_money - ' . $val['total_money'])
                        ]);
                    PurchaseOrderSub::where([['order_id', $order['order_id']], ['cpid', $cpid], ['id', $val['sub_order_id']]])
                        ->update(['create_count' => DB::raw('create_count + ' . $val['count']), 'create_weight' => DB::raw('create_weight - ' . $val['total_weight'])]);

                    // //处理待入库相关数据
                    // Stock::doStockIn($cpid, $val['stock_id'], -$val['count'], -$val['total_weight']);
                }
                PurchaseOrderProcess::where([['order_id', $order['order_id']], ['cpid', $cpid]])
                    ->update([
                        'stockin_weight' => DB::raw('stockin_weight - ' . $stockin_weight),
                        'stockin_count' => DB::raw('stockin_count - ' . $stockin_count),
                        'stockin_money' => DB::raw('stockin_money - ' . $stockin_money)
                    ]);
            }


            PurchaseStockinOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid])->whereIn('id', $order_id_arr)->update(['is_del' => 2, 'del_at' => time()]);
            PurchaseStockinOrderSub::where([['cpid', $cpid], ['create_status', '<>', 1]])->whereIn('stockin_order_id', $order_id_arr)->update(['is_del' => 2, 'del_at' => time()]);
            //处理待入库相关

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单删除失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            PurchaseStockinOrderSub::where(['stockin_order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->update($data);
        } else {
            PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 生成入库单
     */
    public function createwarehousingorderold(Request $request)
    {
        //除定尺之外需判断数量分配长度
        // echo json_encode([['sub_order_id'=>1,'create_count'=>'5','create_weight'=>'','lengthwithcount'=>[['length'=>1900,'count'=>1],['length'=>1200,'count'=>4]]],['sub_order_id'=>1,'create_count'=>'2','create_weight'=>'','lengthwithcount'=>[['length'=>900,'count'=>2]]]]);exit;
        $order_id = $request->order_id ?? 0;
        $sub_order = is_array($request->suborder) ? $request->suborder : (is_array(json_decode($request->suborder, true)) ? json_decode($request->suborder, true) : []);
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $remark = $request->remark ?? '';
        $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }


        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可生成入库单']);
        }


        $sub_order_arr = [];
        if (count($sub_order) > 0) {

            foreach ($sub_order as $val) {
                if (!isset($val['sub_order_id']) || $val['sub_order_id'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '无效参数！']);
                }
                if (!isset($val['create_count']) || $val['create_count'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '生成件数不能小于0']);
                }
                $sub_order_info = PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid], ['create_status', 1], ['id', $val['sub_order_id']]])->first();
                if (!$sub_order_info) {
                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                }
                $sub_order_info = $sub_order_info->toArray();
                $lengthwithcount = isset($val['lengthwithcount']) ? (is_array($val['lengthwithcount']) ? $val['lengthwithcount'] : (is_array(json_decode($val['lengthwithcount'], true)) ? json_decode($val['lengthwithcount'], true) : [])) : [];

                if ($sub_order_info['archive_type'] == 1) { //理计

                    //计算重量
                    $length_count = 0;
                    $total_weight = 0;
                    foreach ($lengthwithcount as &$lengthval) {
                        if ($lengthval['length'] <= 0 || $lengthval['count'] <= 0 || $lengthval['sp_num'] == '') {
                            return response()->json(['code' => '001', 'msg' => '理计长度信息有误']);
                        }
                        $length = $lengthval['length'];
                        $count = $lengthval['count'];
                        $length_count = bcadd($length_count, $count);
                        $weight = mathtoweightbyarchivetype($sub_order_info['archive_spec'], $sub_order_info['archive_type'], $length); //kg
                        $total_weight = mathfuncweight('add', $total_weight, mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count)); //kg*10
                        $lengthval['weight'] = mathfuncweight('mul', $weight, 10);
                        $lengthval['total_weight'] = mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count);
                    }
                    if ($length_count != $val['create_count']) {
                        return response()->json(['code' => '001', 'msg' => '长度件数不匹配']);
                    }
                    $sub_order_info['total_weight'] = $total_weight; //kg*10
                    $sub_order_info['weight'] = mathfuncweight('div', $total_weight, $length_count); //kg*10
                }

                if ($sub_order_info['archive_type'] == 3) {
                    $sub_order_info['weight'] = mathfuncweight('mul', $sub_order_info['weight'], 10); //kg*10
                    $sub_order_info['total_weight'] = intval(mathfuncweight('mul', $sub_order_info['weight'], $val['create_count'])); //kg*10
                }

                if ($sub_order_info['archive_type'] == 2) { //过磅
                    $sub_order_info['total_weight'] = mathfuncweight('mul', $val['create_weight'], 10); //kg*10

                    $sub_order_info['weight'] = mathfuncweight('div', $sub_order_info['total_weight'], $val['create_count']); //kg*10
                }

                if ($info->is_band != 1) { //创建订单未绑定协议的，可以修改价格
                    if (!(isset($val['base_price']) && intval($val['base_price']) > 0) || !(isset($val['add_price']) && intval($val['add_price']) >= 0)) {
                        return response()->json(['code' => '001', 'msg' => '无效价格设置']);
                    }

                    $sub_order_info['base_price'] =  $val['base_price'];
                    $sub_order_info['add_price'] =  $val['add_price'];
                    $sub_order_info['price'] =  mathfuncmoney('add', $val['base_price'], $val['add_price']);
                }

                $sub_order_info['lengthwithcount'] = json_encode($lengthwithcount);
                $sub_order_info['create_count'] = $val['create_count'];
                $sub_order_info['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $sub_order_info['total_weight'], 10000, 4), $sub_order_info['price'], 0);


                $sub_order_info['remark'] = isset($val['remark']) ? $val['remark'] : '';
                $sub_order_arr[] = $sub_order_info;
            }
        } else {
            //获取未生成的子订单
            return response()->json(['code' => '001', 'msg' => '子订单不能为空']);
        }



        $maindata = $info->toArray();
        unset($maindata['id']);
        $maindata['order_sn_code'] = SnCode::getSnCode('PWO_');
        $maindata['stockin_order_id'] = $order_id;
        $maindata['stockin_create_at'] = $maindata['create_at'];
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['remark'] = $remark;
        $maindata['is_finance_update'] = 1;
        $suborderdata = [];
        $warehousing_weight = 0;
        $warehousing_count = 0;
        $warehousing_money = 0;
        foreach ($sub_order_arr as $key => $val) {
            $item = [
                'old_sub_id' => $val['id'],
                'sub_order_id' => $val['sub_order_id'],
                'cpid' => $val['cpid'],
                'stock_id' => $val['stock_id'],
                'count' => $val['create_count'],
                'weight' => $val['weight'],
                'total_weight' => $val['total_weight'],
                'price' => $val['price'],
                'base_price' => $val['base_price'],
                'add_price' => $val['add_price'],
                'lengthwithcount' => $val['lengthwithcount'],
                'total_money' => $val['total_money'],
                'warehouse_name' => $val['warehouse_name'],
                'archive_no' => $val['archive_no'],
                'archive_name' => $val['archive_name'],
                'archive_spec' => $val['archive_spec'],
                'archive_material' => $val['archive_material'],
                'steel_factory_name' => $val['steel_factory_name'],
                'breed_name' => $val['breed_name'],
                'archive_type' => $val['archive_type'],
                'remark' => $val['remark'],
                // 'audit_status' => 2 //直接提交审核
            ];
            $warehousing_weight = mathfuncweight('add', $warehousing_weight, $val['total_weight']);
            $warehousing_count = mathfunc('add', $warehousing_count, $val['create_count']);
            $warehousing_money = mathfuncmoney('add', $warehousing_money, $item['total_money']);
            $suborderdata[] = $item;
        }
        DB::beginTransaction();
        try {
            $warehousing_order_id = PurchaseWarehousingOrder::create($maindata)->id;

            // PurchaseOrderProcess::where([['order_id', $info->order_id], ['cpid', $cpid]])
            //     ->update([
            //         'warehousing_weight' => DB::raw('warehousing_weight + ' . $warehousing_weight),
            //         'warehousing_count' => DB::raw('warehousing_count + ' . $warehousing_count),
            //         'warehousing_money' => DB::raw('warehousing_money + ' . $warehousing_money)
            //     ]);
            $old_sub_id_arr = [];
            foreach ($suborderdata as $key => $val) {
                $old_sub_id = $suborderdata[$key]['old_sub_id'];
                unset($suborderdata[$key]['old_sub_id']);
                $suborderdata[$key]['warehousing_order_id'] = $warehousing_order_id;
                PurchaseWarehousingOrderSub::insert($suborderdata[$key]);


                //更新订单执行情况
                // PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])
                //     ->update([
                //         'warehousing_weight' => DB::raw('warehousing_weight + ' . $val['total_weight']),
                //         'warehousing_count' => DB::raw('warehousing_count + ' . $val['count']),
                //         'warehousing_money' => DB::raw('warehousing_money + ' . $val['total_money'])
                //     ]);

                //处理待入库相关数据
                $lengthwithcount = json_decode($val['lengthwithcount'], true);

                foreach ($lengthwithcount as $substock) {
                    Stock::doStockInSub($val['cpid'], $val['stock_id'], $substock['count'], $substock['total_weight'], 1, $substock['length'], $substock['sp_num'], $substock['weight']);
                }

                $old_sub_id_arr[] = $old_sub_id;
            }



            //写入入库付款对账表
            $datawp = [
                'cpid' => $cpid,
                'manger_id' => $info->manger_id,
                'order_id' => $info->order_id,
                'stockin_order_id' => $order_id,
                'warehousing_order_id' => $warehousing_order_id,
                'type' => 1,
                'wo_order_sn_code' => $maindata['order_sn_code'],
                'po_order_sn_code' => $maindata['po_order_sn_code'],
                'order_date' => $maindata['order_date'],
                'total_weight' => $warehousing_weight,
                'total_money' => $warehousing_money,
                'create_at' => time(),
                'update_at' => time(),
            ];
            PurchaseWarehousingOrderwithpay::create($datawp);

            PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid]])->whereIn('id', $old_sub_id_arr)->update(['create_at' => time(), 'create_status' => 2]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info($e->getMessage());
            return response()->json(['code' => '001', 'msg' => '采购订单生成入库单失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '采购订单生成入库单成功']);
    }



    public function createwarehousingorder(Request $request)
    {
        //除定尺之外需判断数量分配长度

        // echo json_encode([['sub_order_id'=>1,'create_count'=>'5','create_weight'=>'','lengthwithcount'=>[['length'=>1900,'count'=>1],['length'=>1200,'count'=>4]]],['sub_order_id'=>1,'create_count'=>'2','create_weight'=>'','lengthwithcount'=>[['length'=>900,'count'=>2]]]]);exit;
        $order_id = $request->order_id ?? 0;
        $sub_order = is_array($request->suborder) ? $request->suborder : (is_array(json_decode($request->suborder, true)) ? json_decode($request->suborder, true) : []);
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $remark = $request->remark ?? '';
        $info = PurchaseStockinOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }


        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可生成入库单']);
        }

        $RDRecordDetails = []; //入库单-明细行信息
        $sub_order_arr = [];
        if (count($sub_order) > 0) {

            if ($info->is_form_sale == 2) {
                if (count($sub_order) != count($info->suborder()->get()->toArray())) {

                    return response()->json(['code' => '001', 'msg' => '自采订单不可拆分']);
                }
            }


            foreach ($sub_order as $val) {
                if (!isset($val['sub_order_id']) || $val['sub_order_id'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '无效参数！']);
                }
                if (!isset($val['create_count']) || $val['create_count'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '生成件数不能小于0']);
                }
                $sub_order_info = PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid], ['create_status', 1], ['id', $val['sub_order_id']]])->first();
                if (!$sub_order_info) {
                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                }
                $sub_order_info = $sub_order_info->toArray();
                $sub_sub_order = isset($val['sub_sub_order']) ? (is_array($val['sub_sub_order']) ? $val['sub_sub_order'] : (is_array(json_decode($val['sub_sub_order'], true)) ? json_decode($val['sub_sub_order'], true) : [])) : [];


                if ($info->is_band != 1) { //创建订单未绑定协议的，可以修改价格
                    if (!(isset($val['base_price']) && intval($val['base_price']) > 0) || !(isset($val['add_price']) && intval($val['add_price']) >= 0)) {
                        return response()->json(['code' => '001', 'msg' => '无效价格设置']);
                    }

                    $sub_order_info['base_price'] =  $val['base_price'];
                    $sub_order_info['add_price'] =  $val['add_price'];
                    $sub_order_info['price'] =  mathfuncmoney('add', $val['base_price'], $val['add_price']);
                }

                if ($sub_order_info['archive_type'] == 1) { //理计

                    //计算重量
                    $length_count = 0;
                    $total_weight = 0;
                    foreach ($sub_sub_order as &$subsubval) {
                        if (
                            $subsubval['length'] <= 0 || $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                            || $subsubval['origin'] == ''  || $subsubval['layer_num'] == ''
                        ) {
                            return response()->json(['code' => '001', 'msg' => '理计码单信息有误']);
                        }

                        $subsubval['warehousing_at'] = ''; // ✅ 新增这一行，添加时间戳
                        $subsubval['create_at'] = time(); // ✅ 新增这一行，添加时间戳

                        $length = $subsubval['length'];
                        $count = $subsubval['count'];
                        $length_count = bcadd($length_count, $count);
                        $weight = mathtoweightbyarchivetype($sub_order_info['archive_spec'], $sub_order_info['archive_type'], $length); //kg
                        $total_weight = mathfuncweight('add', $total_weight, mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count)); //kg*10
                        $subsubval['weight'] = mathfuncweight('mul', $weight, 10);
                        $subsubval['total_weight'] = mathfuncweight('mul', mathfuncweight('mul', $weight, 10), $count);
                        $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $sub_order_info['price'], 0);
                    }
                    if ($length_count != $val['create_count']) {
                        return response()->json(['code' => '001', 'msg' => '理计码单长度件数不匹配']);
                    }
                    $sub_order_info['total_weight'] = $total_weight; //kg*10
                    $sub_order_info['weight'] = mathfuncweight('div', $total_weight, $length_count); //kg*10
                }

                if ($sub_order_info['archive_type'] == 3) {


                    $length_count = 0;
                    foreach ($sub_sub_order as &$subsubval) {
                        if (
                            $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                            || $subsubval['origin'] == ''  || $subsubval['layer_num'] == ''
                        ) {
                            return response()->json(['code' => '001', 'msg' => '定尺码单信息有误']);
                        }

                        $subsubval['warehousing_at'] = ''; // ✅ 新增这一行，添加时间戳
                        $subsubval['create_at'] = time(); // ✅ 新增这一行，添加时间戳

                        $count = $subsubval['count'];
                        $length_count = bcadd($length_count, $count);

                        $subsubval['weight'] = mathfuncweight('mul', $sub_order_info['weight'], 10); //kg*10
                        $subsubval['total_weight'] = intval(mathfuncweight('mul', $subsubval['weight'], $subsubval['count']));
                        $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $sub_order_info['price'], 0);
                    }
                    if ($length_count != $val['create_count']) {
                        return response()->json(['code' => '001', 'msg' => '定尺码单入库件数不匹配']);
                    }

                    $sub_order_info['weight'] = mathfuncweight('mul', $sub_order_info['weight'], 10); //kg*10
                    $sub_order_info['total_weight'] = intval(mathfuncweight('mul', $sub_order_info['weight'], $val['create_count'])); //kg*10
                }

                if ($sub_order_info['archive_type'] == 2) { //过磅


                    //计算重量
                    $length_count = 0;
                    $total_weight = 0;
                    foreach ($sub_sub_order as &$subsubval) {
                        if (
                            $subsubval['count'] <= 0 || $subsubval['stock_num'] == ''
                            || $subsubval['origin'] == ''  || $subsubval['layer_num'] == '' || $subsubval['total_weight'] <= 0
                        ) {
                            return response()->json(['code' => '001', 'msg' => '过磅码单信息有误']);
                        }
                        $subsubval['warehousing_at'] = ''; // ✅ 新增这一行，添加时间戳
                        $subsubval['create_at'] = time(); // ✅ 新增这一行，添加时间戳

                        $subsubval['length'] = isset($subsubval['length']) ? $subsubval['length'] : 0;

                        $subsubval['total_weight'] = mathfuncweight('mul', $subsubval['total_weight'], 10); //kg*10
                        $subsubval['weight'] = intval(mathfuncweight('div', $subsubval['total_weight'], $subsubval['count']));
                        $subsubval['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $subsubval['total_weight'], 10000, 4), $sub_order_info['price'], 0);
                    }



                    $sub_order_info['total_weight'] = mathfuncweight('mul', $val['create_weight'], 10); //kg*10

                    $sub_order_info['weight'] = mathfuncweight('div', $sub_order_info['total_weight'], $val['create_count']); //kg*10
                }



                $sub_order_info['sub_sub_order'] = json_encode($sub_sub_order);
                $sub_order_info['create_count'] = $val['create_count'];
                $sub_order_info['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $sub_order_info['total_weight'], 10000, 4), $sub_order_info['price'], 0);


                $sub_order_info['remark'] = isset($val['remark']) ? $val['remark'] : '';
                $sub_order_arr[] = $sub_order_info;
            }
        } else {
            //获取未生成的子订单
            return response()->json(['code' => '001', 'msg' => '子订单不能为空']);
        }



        $maindata = $info->toArray();
        unset($maindata['id']);
        $maindata['order_sn_code'] = SnCode::getSnCode('PWO_');
        $maindata['stockin_order_id'] = $order_id;
        $maindata['stockin_create_at'] = $maindata['create_at'];
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['remark'] = $remark;
        $maindata['is_finance_update'] = 1;
        $maindata['create_manger_id'] = $this->mangerinfo['id'];

        $suborderdata = [];
        $warehousing_weight = 0;
        $warehousing_count = 0;
        $warehousing_money = 0;
        foreach ($sub_order_arr as $key => $val) {
            $item = [
                'old_sub_id' => $val['id'],
                'sub_order_id' => $val['sub_order_id'],
                'cpid' => $val['cpid'],
                'stock_id' => $val['stock_id'],
                'count' => $val['create_count'],
                'weight' => $val['weight'],
                'total_weight' => $val['total_weight'],
                'price' => $val['price'],
                'base_price' => $val['base_price'],
                'add_price' => $val['add_price'],
                'sub_sub_order' => $val['sub_sub_order'],
                'total_money' => $val['total_money'],
                'warehouse_name' => $val['warehouse_name'],
                'archive_no' => $val['archive_no'],
                'archive_name' => $val['archive_name'],
                'archive_spec' => $val['archive_spec'],
                'archive_material' => $val['archive_material'],
                'steel_factory_name' => $val['steel_factory_name'],
                'breed_name' => $val['breed_name'],
                'archive_type' => $val['archive_type'],
                'remark' => $val['remark'],
                // 'audit_status' => 2 //直接提交审核
            ];
            $warehousing_weight = mathfuncweight('add', $warehousing_weight, $val['total_weight']);
            $warehousing_count = mathfunc('add', $warehousing_count, $val['create_count']);
            $warehousing_money = mathfuncmoney('add', $warehousing_money, $item['total_money']);
            $suborderdata[] = $item;

            //Stock::where("id",$val['stock_id'])
            $RDRecordDetails[] = [
                "Warehouse" => ["Code" => WarehouseList::where(["warehouse_name" => $val['warehouse_name'], "cpid" => $cpid])->value("warehouse_no")],
                "Inventory" => ["Code" => $val['archive_no']],
                "Unit" => ["Code" => "001", "Name" => "吨"],
                "Quantity" => $val['create_count'],
                "Amount" => $val['total_money'],
                "DynamicPropertyKeys" => ["pubuserdefnvc1", "pubuserdefnvc2", "pubuserdefnvc3"],
                "DynamicPropertyValues" => [$val['steel_factory_name'], $val['breed_name'], $val['archive_material']],
            ];
        }
        DB::beginTransaction();
        try {
            $warehousing_order_id = PurchaseWarehousingOrder::create($maindata)->id;

            // PurchaseOrderProcess::where([['order_id', $info->order_id], ['cpid', $cpid]])
            //     ->update([
            //         'warehousing_weight' => DB::raw('warehousing_weight + ' . $warehousing_weight),
            //         'warehousing_count' => DB::raw('warehousing_count + ' . $warehousing_count),
            //         'warehousing_money' => DB::raw('warehousing_money + ' . $warehousing_money)
            //     ]);
            $old_sub_id_arr = [];
            foreach ($suborderdata as $key => $val) {
                $old_sub_id = $suborderdata[$key]['old_sub_id'];
                unset($suborderdata[$key]['old_sub_id']);
                $suborderdata[$key]['warehousing_order_id'] = $warehousing_order_id;
                PurchaseWarehousingOrderSub::insert($suborderdata[$key]);


                //更新订单执行情况
                // PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $val['sub_order_id']]])
                //     ->update([
                //         'warehousing_weight' => DB::raw('warehousing_weight + ' . $val['total_weight']),
                //         'warehousing_count' => DB::raw('warehousing_count + ' . $val['count']),
                //         'warehousing_money' => DB::raw('warehousing_money + ' . $val['total_money'])
                //     ]);

                //处理待入库相关数据
                // $sub_sub_order = json_decode($val['sub_sub_order'], true);

                // foreach ($sub_sub_order as $substock) {
                //     Stock::doStockInSub($val['cpid'], $val['stock_id'], $substock['count'], $substock['total_weight'], 1, $substock['length'], $substock['sp_num'], $substock['weight']);
                // }

                Stock::doStockIn($cpid, $val['stock_id'], $val['count'], $val['total_weight']);

                $old_sub_id_arr[] = $old_sub_id;
            }



            //写入入库付款对账表
            $datawp = [
                'cpid' => $cpid,
                'manger_id' => $info->manger_id,
                'order_id' => $info->order_id,
                'stockin_order_id' => $order_id,
                'warehousing_order_id' => $warehousing_order_id,
                'type' => 1,
                'wo_order_sn_code' => $maindata['order_sn_code'],
                'po_order_sn_code' => $maindata['po_order_sn_code'],
                // 'company_name'=>$maindata['company_name'],
                'custom_id'=>$maindata['custom_id'],
                'order_date' => $maindata['order_date'],
                'total_weight' => $warehousing_weight,
                'total_money' => $warehousing_money,
                'create_at' => time(),
                'update_at' => time(),
            ];
            PurchaseWarehousingOrderwithpay::create($datawp);

            PurchaseStockinOrderSub::where([['stockin_order_id', $order_id], ['cpid', $cpid]])->whereIn('id', $old_sub_id_arr)->update(['create_at' => time(), 'create_status' => 2]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info($e->getMessage());
            return response()->json(['code' => '001', 'msg' => '采购订单生成入库单失败' . $e->getMessage()]);
        }
        /**
         *
         *  采购入库单 T+ 生成 进货单  2025.02.07
         *
         *  增加多仓库订单入库
         *
        */
//        $Chanjet_param = [
//          "dto" => [
//              "ExternalCode" => $maindata['order_sn_code'],
//              "Code" => "",
//              "IsModifiedCode" => "true",
//              "VoucherDate" => date('Y-m-d'),
//              "VoucherType" => ["Code"=>"ST1001"],
//              "BusiType" => ["Code" => "01"],
//              "Partner" => ["Code" => Custom::where('id',$info['custom_id'])->value("company_code")],
//              "Warehouse" => ["Code"=>$RDRecordDetails[0]["Warehouse"]["Code"]],
//              "RDRecordDetails"=>$RDRecordDetails,
//          ]
//        ];

//        if($this->mangerinfo['org_id']){
//            ChanjetRequest::getInstance()->purchaseReceiveCreate($Chanjet_param,$this->mangerinfo['org_id']);
//
//        }

        return response()->json(['code' => '000', 'msg' => '采购订单生成入库单成功']);
    }
}
